<template>
  <ErrorBoundary>
    <div class="delivery-app">
      <!-- 首页 - 配送单管理主界面 -->
      <div class="delivery-main">
        <div class="main-header">
          <h1>配送单管理</h1>
          <div class="header-actions">
            <button class="new-delivery-btn" @click="showCreateDelivery = true">
              <span class="btn-icon">+</span>
              新建配送单
            </button>
            <button class="container-manage-btn" @click="currentView = 'containers'">
              <span class="btn-icon">📦</span>
              容器管理
            </button>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="loading">
          <p>正在加载数据...</p>
        </div>
        
        <!-- 错误提示 -->
        <div v-if="error" class="error-message">
          <p>{{ error }}</p>
          <button @click="retryCurrentOperation" class="retry-btn">重试</button>
        </div>
        
        <!-- 筛选控制 -->
        <div class="filter-controls">
          <button class="filter-toggle-btn" @click="toggleFilterPanel">
            筛选 <span v-if="hasActiveFilters" class="filter-count">{{ getActiveFilterCount() }}</span>
          </button>
        </div>
        
        <!-- 筛选面板 -->
        <div v-if="showFilterPanel" class="filter-panel">
          <div class="filter-row">
            <div class="filter-item">
              <label>配送方式:</label>
              <select v-model="filters.deliveryMethod" @change="applyFilters">
                <option value="">全部</option>
                <option value="仓库配送">仓库配送</option>
                <option value="货主自提">货主自提</option>
              </select>
            </div>
            <div class="filter-item">
              <label>状态:</label>
              <select v-model="filters.status" @change="applyFilters">
                <option value="">全部</option>
                <option value="pending">待处理</option>
                <option value="in_progress">配送中</option>
                <option value="completed">已完成</option>
              </select>
            </div>
          </div>
          <div class="filter-actions">
            <button class="clear-filters-btn" @click="clearFilters">清除筛选</button>
            <button class="close-filter-btn" @click="showFilterPanel = false">收起筛选</button>
          </div>
        </div>
        
        <!-- 配送单列表 -->
        <div class="order-items">
          <div 
            v-for="order in filteredDeliveryOrders" 
            :key="order.id"
            class="order-item"
            @click="viewOrderDetail(order)"
          >
            <div class="order-info">
              <div class="order-number">配送单号: {{ order.orderNumber || order.id }}</div>
              <div class="destination-display">
                <span class="destination-label">发运目的地</span>
                <span class="destination-value">{{ order.destination || '未设置' }}</span>
              </div>
              
              <!-- PC端展开按钮 - 放在发运目的地下方 -->
              <div class="toggle-btn-container pc-toggle">
                <button class="toggle-btn" @click.stop="toggleOrderExpansion(order.id)">
                  <span class="toggle-text">{{ isOrderExpanded(order.id) ? '收起详细信息' : '详细信息' }}</span>
                  <span class="toggle-icon" :class="{ 'expanded': isOrderExpanded(order.id) }">▼</span>
                </button>
              </div>
              
              <div class="order-meta" :class="{ 'mobile-collapsed': !isOrderExpanded(order.id) }">
                <!-- 基础配送信息 -->
                <div class="meta-item priority-info">
                  <span class="meta-label">配送方式</span>
                  <span class="meta-value">{{ order.deliveryMethod || order.method }}</span>
                </div>
                <div class="meta-item priority-info">
                  <span class="meta-label">司机</span>
                  <span class="meta-value">{{ order.driverName || '未指定' }}</span>
                </div>
                <div class="meta-item priority-info">
                  <span class="meta-label">车牌号</span>
                  <span class="meta-value vehicle-plate">{{ order.vehicleInfo || '未指定' }}</span>
                </div>
                
                <!-- 联系信息 -->
                <div class="meta-item contact-info">
                  <span class="meta-label">手机号</span>
                  <span class="meta-value phone-number">{{ order.phoneNumber || '未填写' }}</span>
                </div>
                
                <!-- 容器详情 -->
                <div class="meta-item">
                  <span class="meta-label">商品种数</span>
                  <span class="meta-value product-count">{{ order.productCountDisplay || (order.containerCount || 0) + '种商品' }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">存放商品数</span>
                  <span class="meta-value stored-product-count">{{ order.storedProductCountDisplay || (order.storedProductCount || 0) + '个' }}</span>
                </div>
                
                <!-- 拥有容器信息 -->
                <div v-if="hasContainerCodes(order)" class="meta-item full-width container-codes-section">
                  <span class="meta-label">拥有容器</span>
                  <span class="meta-value container-codes">
                    <span class="container-codes-text">{{ getContainerCodesDisplay(order) }}</span>
                  </span>
                </div>
                
                <!-- 物理规格 -->
                <div class="meta-item">
                  <span class="meta-label">总体积</span>
                  <span class="meta-value volume">{{ order.volumeDisplay || '计算中...' }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">总重量</span>
                  <span class="meta-value weight">{{ order.weightDisplay || '计算中...' }}</span>
                </div>
                
                <!-- 时间和状态信息 -->
                <div class="meta-item">
                  <span class="meta-label">创建时间</span>
                  <span class="meta-value">{{ formatDate(order.createdAt) }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">状态</span>
                  <span class="meta-value status" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</span>
                </div>
              </div>
            </div>
            
            <!-- 移动端展开按钮 - 放在操作按钮上方 -->
            <div class="toggle-btn-container mobile-toggle">
              <button class="toggle-btn" @click.stop="toggleOrderExpansion(order.id)">
                <span class="toggle-text">{{ isOrderExpanded(order.id) ? '收起详细信息' : '详细信息' }}</span>
                <span class="toggle-icon" :class="{ 'expanded': isOrderExpanded(order.id) }">▼</span>
              </button>
            </div>
            
            <div class="order-actions">
              <button 
                v-if="!isOrderShipped(order)"
                class="action-btn modify-btn" 
                @click.stop="showModifyOrder(order)"
              >
                修改配送单
              </button>
              <button 
                class="action-btn" 
                @click.stop="processOrder(order)"
                :disabled="isOrderShipped(order)"
                :class="{ 'shipped': isOrderShipped(order) }"
              >
                {{ isOrderShipped(order) ? '已发运' : '确认发运' }}
              </button>
            </div>
          </div>
        </div>
      </div>


      <!-- 容器管理弹窗 -->
      <div v-if="currentView === 'containers'" class="modal-overlay" @click="backToMain">
        <div class="modal-content large container-modal" @click.stop>
          <div class="modal-header">
            <h3>容器管理</h3>
            <button class="close-btn" @click="backToMain">×</button>
          </div>
          
          <div class="container-modal-actions">
            <div class="filter-info">
              <span class="filter-badge">筛选条件: 仅显示使用中的容器</span>
              <span class="container-count">{{ filteredContainers.length }} 个容器</span>
            </div>
            <button class="refresh-btn" @click="loadContainers">刷新</button>
          </div>
          
          <div v-if="loadingContainers" class="loading">
            <p>正在加载容器信息...</p>
          </div>
          
          <div class="container-items">
            <div 
              v-for="container in filteredContainers" 
              :key="container.id"
              class="container-item"
            >
              <div class="container-info">
                <div class="container-id">容器码: {{ getContainerCodeDisplay(container) }}</div>
                <div class="container-site" v-if="getContainerSiteInfo(container)">
                  <strong>配送站点:</strong>
                  <span class="site-info">{{ getContainerSiteInfo(container) }}</span>
                </div>
                <div class="container-products" v-if="container.products">
                  <strong>商品信息:</strong>
                  <div class="product-detail">{{ container.products }}</div>
                </div>
                <div v-else class="no-products">暂无商品信息</div>
              </div>
            </div>
            
            <!-- 无符合条件容器时的提示信息 -->
            <div v-if="!loadingContainers && filteredContainers.length === 0" class="empty-containers-message">
              <div class="empty-icon">📦</div>
              <div class="empty-text">
                <h4>暂无使用中的容器</h4>
                <p>当前筛选条件下没有找到状态为"使用中"的容器</p>
                <p class="hint-text">
                  数据库中共有 {{ containers.length }} 个容器，其中 {{ containers.length }} 个为"待使用"状态
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

    <!-- 新建配送单弹窗 -->
    <div v-if="showCreateDelivery" class="modal-overlay" @click="closeCreateModal">
      <div class="modal-content large" @click.stop>
        <div class="modal-header">
          <h3>新建配送单</h3>
          <button class="close-btn" @click="closeCreateModal">×</button>
        </div>
        
        <form @submit.prevent="createDeliveryOrder" class="delivery-form">
          <div class="form-group">
            <label class="form-label">配送方式 *</label>
            <select v-model="newDelivery.method" class="form-control" required>
              <option value="">请选择配送方式</option>
              <option value="仓库配送">仓库配送</option>
              <option value="货主自提">货主自提</option>
            </select>
            <div class="error" v-if="formErrors.method">{{ formErrors.method }}</div>
          </div>
          
          <div v-if="newDelivery.method === '仓库配送'" class="form-group">
            <label class="form-label">发运目的地 *</label>
            <select v-model="newDelivery.destination" class="form-control" :required="newDelivery.method === '仓库配送'">
              <option value="">请选择发运目的地</option>
              <option 
                v-for="site in filteredDeliverySites" 
                :key="site.id" 
                :value="site.siteInfo"
              >
                {{ site.siteInfo }}
              </option>
            </select>
            <div class="error" v-if="formErrors.destination">{{ formErrors.destination }}</div>
          </div>
          
          <div v-else-if="newDelivery.method === '货主自提'" class="form-group">
            <label class="form-label">发运目的地</label>
            <input 
              type="text" 
              value="---自提" 
              class="form-control" 
              disabled
              style="background-color: #f8f9fa; color: #666;"
            />
            <small class="form-text text-muted">货主自提模式，发运目的地固定为"---自提"</small>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">选择司机 *</label>
              <select v-model="newDelivery.driver" class="form-control" required>
                <option value="">请选择司机</option>
                <option v-for="driver in drivers" :key="driver.id" :value="driver.id">
                  {{ driver.displayText }}
                </option>
              </select>
              <div class="error" v-if="formErrors.driver">{{ formErrors.driver }}</div>
            </div>
            <div class="form-group">
              <label class="form-label">选择车辆 *</label>
              <select v-model="newDelivery.vehicle" class="form-control" required>
                <option value="">请选择车辆</option>
                <option v-for="vehicle in vehicles" :key="vehicle.id" :value="vehicle.id">
                  {{ vehicle.displayText }}
                </option>
              </select>
              <div class="error" v-if="formErrors.vehicle">{{ formErrors.vehicle }}</div>
            </div>
          </div>
        </form>
        
        <!-- 容器筛选组件 - 放在司机选择和表单提交按钮之间 -->
        <div class="container-selection-section">
          <ContainerFilter
            v-if="newDelivery.method === '仓库配送'"
            v-model="containerSelection"
            :delivery-sites="deliverySites"
            :external-destination="newDelivery.destination"
            :show-selected-containers="false"
            :show-container-sites="false"
            :used-container-codes="usedContainerCodes"
            :editing-delivery-order-id="''"
            @container-selected="handleContainerSelected"
            class="container-filter-section"
          />
          
          <!-- 货主自提时的容器选择 -->
          <ContainerFilter
            v-else-if="newDelivery.method === '货主自提'"
            v-model="containerSelection"
            :delivery-sites="deliverySites"
            external-destination="---自提"
            :show-selected-containers="false"
            :show-container-sites="false"
            :used-container-codes="usedContainerCodes"
            :editing-delivery-order-id="''"
            @container-selected="handleContainerSelected"
            class="container-filter-section"
          />
          
          <!-- 容器选择错误信息 -->
          <div v-if="formErrors.container" class="error container-error">
            {{ formErrors.container }}
          </div>
        </div>
        
        <div class="form-actions">
          <button type="button" class="cancel-btn" @click="closeCreateModal">取消</button>
          <button type="button" class="submit-btn" :disabled="creatingOrder" @click="createDeliveryOrder">
            {{ creatingOrder ? '发送中...' : '发送创建请求' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 容器选择弹窗 -->
    <div v-if="showContainerSelection" class="modal-overlay" @click="closeContainerModal">
      <div class="modal-content large" @click.stop>
        <div class="modal-header">
          <h3>选择配送容器</h3>
          <button class="close-btn" @click="closeContainerModal">×</button>
        </div>
        
        <div v-if="loadingContainers" class="loading">
          正在加载容器信息...
        </div>
        
        <div v-else class="container-selection">
          <div 
            v-for="container in availableContainers" 
            :key="container.id"
            class="selectable-container"
            :class="{ selected: selectedContainer?.id === container.id }"
            @click="selectContainer(container)"
          >
            <div class="container-info">
              <div class="container-id">容器码: {{ getContainerCodeDisplay(container) }}</div>
              <div class="container-site" v-if="getContainerSiteInfo(container)">
                <strong>配送站点:</strong>
                <span class="site-info">{{ getContainerSiteInfo(container) }}</span>
              </div>
              <div class="container-products" v-if="container.products">
                <strong>商品信息:</strong>
                <div class="product-detail">{{ container.products }}</div>
              </div>
              <div v-else class="no-products">暂无商品信息</div>
            </div>
          </div>
        </div>
        
        <div class="modal-actions">
          <button class="cancel-btn" @click="closeContainerModal">取消</button>
          <button class="confirm-btn" @click="confirmContainerSelection" :disabled="!selectedContainer">
            确认选择
          </button>
        </div>
      </div>
    </div>

    <!-- 修改配送单弹窗 -->
    <div v-if="showModifyDelivery" class="modal-overlay" @click="closeModifyModal">
      <div class="modal-content large" @click.stop>
        <div class="modal-header">
          <h3>修改配送单</h3>
          <button class="close-btn" @click="closeModifyModal">×</button>
        </div>
        
        <div class="modify-order-info">
          <div class="order-basic-info">
            <div><strong>配送单号：</strong>{{ currentModifyOrder?.orderNumber || currentModifyOrder?.id }}</div>
            <div><strong>发运目的地：</strong>{{ currentModifyOrder?.destination || '未设置' }}</div>
            <div><strong>配送方式：</strong>{{ currentModifyOrder?.deliveryMethod || currentModifyOrder?.method }}</div>
          </div>
        </div>
        
        <!-- 已选择的容器维度 -->
        <div v-if="currentModifyOrder?.containerCodes && currentModifyOrder.containerCodes.length > 0" class="selected-containers-dimension">
          <div class="dimension-header">
            <h4 class="dimension-title">
              <span class="icon">📦</span>
              已选择的容器
            </h4>
            <span class="container-count-badge">{{ currentModifyOrder.containerCodes.length }}个</span>
          </div>
          <div class="container-codes-grid">
            <div 
              v-for="(containerCode, index) in currentModifyOrder.containerCodes" 
              :key="`selected-${containerCode}-${index}`"
              class="container-code-item"
              :class="{ 'selected': isContainerCodeSelected(containerCode), 'deselected': isContainerCodeDeselected(containerCode) }"
              @click="toggleContainerCodeSelection(containerCode)"
            >
              <span class="container-code">{{ containerCode }}</span>
              <span class="selection-status">
                <span v-if="isContainerCodeSelected(containerCode)" class="status-icon selected">✓</span>
                <span v-else-if="isContainerCodeDeselected(containerCode)" class="status-icon deselected">✕</span>
                <span v-else class="status-icon neutral">○</span>
              </span>
            </div>
          </div>
        </div>
        
        <!-- 容器筛选组件 -->
        <div class="container-selection-section">
          <ContainerFilter
            v-model="modifyContainerSelection"
            :delivery-sites="deliverySites"
            :external-destination="currentModifyOrder?.destination || ''"
            :initial-containers="currentModifyOrder?.containerCodes || []"
            :show-selected-containers="true"
            :show-container-sites="true"
            :editing-delivery-order-id="currentModifyOrder?.id || currentModifyOrder?.orderNumber || ''"
            :used-container-codes="usedContainerCodes"
            :is-modify-mode="true"
            @container-selected="handleModifyContainerSelected"
            class="container-filter-section"
          />
          
          <!-- 容器选择错误信息 -->
          <div v-if="modifyFormErrors.container" class="error container-error">
            {{ modifyFormErrors.container }}
          </div>
        </div>
        
        <div class="form-actions">
          <button type="button" class="cancel-btn" @click="closeModifyModal">取消</button>
          <button type="button" class="submit-btn" :disabled="updatingOrder" @click="updateDeliveryOrder">
            {{ updatingOrder ? '更新中...' : '保存修改' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 确认弹窗 -->
    <div v-if="showConfirmModal" class="modal-overlay" @click="closeConfirmModal">
      <div class="modal-content" @click.stop>
        <h3>{{ confirmTitle }}</h3>
        <p>{{ confirmMessage }}</p>
        <div class="modal-actions">
          <button class="cancel-btn" @click="closeConfirmModal">取消</button>
          <button class="confirm-btn" @click="confirmAction">确认</button>
        </div>
      </div>
    </div>
    </div>
  </ErrorBoundary>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import deliveryApi from "./api/delivery.js";
import ContainerFilter from "./components/ContainerFilter.vue";
import ErrorBoundary from "./components/ErrorBoundary.vue";
import { 
  WORKSHEET_IDS, 
  CONTAINER_FIELDS,
  WEBHOOKS,
  getFieldValue
} from "./config/delivery-config.js";

// 视图状态
const currentView = ref('main')
const showCreateDelivery = ref(false)
const showModifyDelivery = ref(false)
const showContainerSelection = ref(false)
const showConfirmModal = ref(false)

// 数据状态
const deliveryOrders = ref([])
const deliverySites = ref([])
const containers = ref([])
const drivers = ref([])
const vehicles = ref([])
const availableContainers = ref([])
const selectedContainer = ref(null)
const usedContainerCodes = ref([]) // 新增：已被其他配送单使用的容器码列表

// 容器详细信息缓存
const containerDetailsCache = ref(new Map())

// 加载状态
const loading = ref(false)
const loadingContainers = ref(false)
const creatingOrder = ref(false)
const updatingOrder = ref(false)

// 错误和调试
const error = ref('')

// 筛选相关
const showFilterPanel = ref(false)
const filters = ref({
  deliveryMethod: '',
  status: ''
})

// 表单数据
const newDelivery = ref({
  method: '',
  destination: '',
  driver: '',
  vehicle: '',
  container: ''
})

// 容器筛选数据
const containerSelection = ref({
  destination: '',
  containers: [], // 改为数组支持多选
  container: '' // 保留兼容性
})

// 修改配送单数据
const currentModifyOrder = ref(null)
const modifyContainerSelection = ref({
  destination: '',
  containers: [],
  container: ''
})

// 修改配送单中的容器状态管理
const selectedContainerCodes = ref([])  // 当前选中的容器码
const removedContainerCodes = ref([])   // 被取消选择的容器码

const modifyFormErrors = ref({
  container: ''
})

const formErrors = ref({
  method: '',
  destination: '',
  driver: '',
  vehicle: '',
  container: ''
})

// 确认弹窗
const confirmTitle = ref('')
const confirmMessage = ref('')
const confirmType = ref('')
const confirmData = ref(null)

// 移动端展开状态管理
const expandedOrdersMap = ref({})

// 计算属性
const filteredDeliveryOrders = computed(() => {
  if (!displayOrders.value || displayOrders.value.length === 0) {
    return []
  }
  
  return displayOrders.value.filter(order => {
    // 配送方式筛选
    if (filters.value.deliveryMethod && 
        order.deliveryMethod !== filters.value.deliveryMethod) {
      return false
    }
    
    // 状态筛选
    if (filters.value.status && 
        order.status !== filters.value.status) {
      return false
    }
    
    return true
  })
})

// 新增：过滤容器以只显示"使用中"状态的容器
const filteredContainers = computed(() => {
  if (!containers.value || containers.value.length === 0) {
    console.log('=== 容器筛选：无容器数据 ===')
    return []
  }
  
  console.log('=== 开始容器状态筛选 ===')
  console.log('原始容器总数:', containers.value.length)
  
  const filtered = containers.value.filter((container, index) => {
    // 获取容器状态
    const status = getContainerStatus(container)
    const isMatch = isContainerStatusInUse(status)
    
    // 详细调试信息
    if (index < 5) { // 只显示前5个容器的调试信息
      console.log(`容器${index + 1}: 状态="${status}", 匹配结果=${isMatch}`)
    }
    
    // 只显示状态为"使用中"的容器
    return isMatch
  })
  
  console.log('筛选后容器数量:', filtered.length)
  console.log('=== 容器状态筛选完成 ===')
  
  return filtered
})

const hasActiveFilters = computed(() => {
  return filters.value.deliveryMethod || filters.value.status
})

// 过滤配送站点，排除自提选项
const filteredDeliverySites = computed(() => {
  return deliverySites.value.filter(site => {
    // 排除站点信息为"自提"或"---自提"的选项
    return site.siteInfo && site.siteInfo !== '自提' && site.siteInfo !== '---自提'
  })
})

// 配送单信息（直接使用API返回的汇总数据）
const displayOrders = ref([])

// 页面生命周期
onMounted(async () => {
  // 添加全局错误处理
  window.addEventListener('error', (event) => {
    console.error('全局错误捕获:', event.error)
  })
  
  window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise拒绝:', event.reason)
    // 防止错误传播到控制台
    event.preventDefault()
  })
  
  // 移动端优化：检测网络连接状态
  if (navigator.onLine === false) {
    error.value = '网络连接断开，请检查网络设置'
    console.warn('设备处于离线状态')
    return
  }

  // 移动端优化：添加网络状态监听
  window.addEventListener('online', () => {
    error.value = ''
    // 网络恢复时重新加载数据
    if (deliveryOrders.value.length === 0) {
      loadDeliveryOrders()
    }
  })

  window.addEventListener('offline', () => {
    error.value = '网络连接已断开'
    console.warn('网络连接已断开')
  })

  // 并发加载数据，但确保错误处理
  try {
    await Promise.allSettled([
      loadDeliveryOrders(),
      loadDeliverySites(),
      loadDrivers(),
      loadVehicles(),
      loadContainers()
    ])
  } catch (err) {
    console.error('初始化数据加载失败:', err)
    error.value = `初始化失败: ${err.message}`
  }
})

// API相关方法

async function loadDeliveryOrders() {
  // 参考JH项目：防止重复加载
  if (loading.value) {
    return
  }

  loading.value = true
  error.value = ''
  
  try {
    
    // 移动端优化：检查网络状态
    if (!navigator.onLine) {
      throw new Error('网络连接不可用，请检查网络设置')
    }
    
    const result = await deliveryApi.getDeliveryOrders()
    
    if (result && Array.isArray(result)) {
      // 清空之前的数据，避免重复
      deliveryOrders.value = []
      deliveryOrders.value = result
      
      // 直接使用API返回的数据，包含汇总字段
      displayOrders.value = result
    } else {
      deliveryOrders.value = []
      displayOrders.value = []
      error.value = '未获取到配送单数据'
    }
  } catch (err) {
    console.error('加载配送单失败:', err)
    error.value = `加载失败: ${err.message}`
    deliveryOrders.value = []
  } finally {
    // 参考JH项目：确保loading状态在finally中重置
    loading.value = false
  }
}

async function loadDeliverySites() {
  try {
    const result = await deliveryApi.getDeliverySites()
    
    if (result && Array.isArray(result)) {
      deliverySites.value = result
    } else {
      deliverySites.value = []
    }
  } catch (err) {
    console.error('加载配送站点失败:', err)
  }
}

async function loadDrivers() {
  try {
    const result = await deliveryApi.getDrivers()
    
    if (result && Array.isArray(result)) {
      drivers.value = result
    } else {
      drivers.value = []
    }
  } catch (err) {
    console.error('加载司机失败:', err)
  }
}

async function loadVehicles() {
  try {
    const result = await deliveryApi.getVehicles()
    
    if (result && Array.isArray(result)) {
      vehicles.value = result
    } else {
      vehicles.value = []
    }
  } catch (err) {
    console.error('加载车辆失败:', err)
  }
}

//  加载已被其他配送单使用的容器码列表
async function loadUsedContainerCodes(excludeOrderId = '') {
  try {
    console.log('=== 加载已使用容器码列表 ===');
    console.log('排除的配送单ID:', excludeOrderId);
    
    const result = await deliveryApi.getUsedContainerCodes(excludeOrderId);
    
    if (result && Array.isArray(result)) {
      usedContainerCodes.value = result;
      console.log(`已加载 ${result.length} 个已使用的容器码:`, result.slice(0, 5));
    } else {
      usedContainerCodes.value = [];
      console.log('未获取到已使用容器码数据');
    }
  } catch (error) {
    console.error('加载已使用容器码失败:', error);
    usedContainerCodes.value = [];
  }
}

async function loadContainers() {
  loadingContainers.value = true
  
  try {
    // 使用容器管理表数据（工作表ID：WORKSHEET_IDS.CONTAINER_MANAGEMENT）
    const result = await deliveryApi.getContainersByWorksheet()
    
    if (result && Array.isArray(result)) {
      containers.value = result
      availableContainers.value = result
    } else {
      containers.value = []
      availableContainers.value = []
    }
  } catch (err) {
    console.error('加载容器失败:', err)
  } finally {
    loadingContainers.value = false
  }
}

// 表单处理
function validateForm() {
  formErrors.value = {
    method: '',
    destination: '',
    driver: '',
    vehicle: '',
    container: ''
  }
  
  let isValid = true
  
  if (!newDelivery.value.method) {
    formErrors.value.method = '请选择配送方式'
    isValid = false
  }
  
  if (newDelivery.value.method === '仓库配送') {
    if (!newDelivery.value.destination) {
      formErrors.value.destination = '请选择发运目的地'
      isValid = false
    }
    if (!containerSelection.value.containers || containerSelection.value.containers.length === 0) {
      formErrors.value.container = '请至少选择一个配送容器'
      isValid = false
    }
  } else if (newDelivery.value.method === '货主自提') {
    // 货主自提固定目的地为"---自提"
    newDelivery.value.destination = '---自提'
    if (!containerSelection.value.containers || containerSelection.value.containers.length === 0) {
      formErrors.value.container = '请至少选择一个配送容器'
      isValid = false
    }
  }
  
  if (!newDelivery.value.driver) {
    formErrors.value.driver = '请选择司机'
    isValid = false
  }
  
  if (!newDelivery.value.vehicle) {
    formErrors.value.vehicle = '请选择车辆'
    isValid = false
  }
  
  return isValid
}

async function createDeliveryOrder() {
  if (!validateForm()) {
    return
  }
  
  creatingOrder.value = true
  
  try {
    // 准备Webhook数据
    const selectedContainers = containerSelection.value.containers || []
    const deliveryData = {
      method: newDelivery.value.method,
      deliveryMethod: newDelivery.value.method,
      destination: newDelivery.value.method === '仓库配送' 
        ? newDelivery.value.destination 
        : newDelivery.value.method === '货主自提' 
        ? '---自提' 
        : '',
      driver: newDelivery.value.driver,
      vehicle: newDelivery.value.vehicle,
      containers: selectedContainers,
      remarks: '',
      createdAt: new Date().toISOString()
    }
    
    console.log('=== 发送配送单创建Webhook ===')
    console.log('配送数据:', deliveryData)
    
    const result = await deliveryApi.createDeliveryOrder(deliveryData)
    
    if (result && result.success) {
      console.log('Webhook发送成功:', result)
      
      // 显示成功信息
      alert('配送单创建请求已发送！\n请稍后在配送单列表中查看新建的配送单。')
      
      // 关闭创建弹窗
      closeCreateModal()
      
      // 延迟刷新配送单列表，给后台工作流一些处理时间
      setTimeout(async () => {
        console.log('刷新配送单列表...')
        await loadDeliveryOrders()
      }, 2000)
      
    } else {
      throw new Error(result.message || 'Webhook发送失败')
    }
  } catch (err) {
    console.error('发送配送单创建Webhook失败:', err)
    alert(`创建配送单请求发送失败: ${err.message}`)
  } finally {
    creatingOrder.value = false
  }
}

// 容器选择
function selectContainer(container) {
  selectedContainer.value = container
}

function confirmContainerSelection() {
  if (!selectedContainer.value) {
    alert('请先选择一个容器')
    return
  }
  
  closeContainerModal()
  
  // 这里可以添加容器与配送单关联的逻辑
  alert(`已选择容器 ${selectedContainer.value.id}`)
}

// 修改配送单相关方法
async function showModifyOrder(order) {
  currentModifyOrder.value = order
  
  console.log('=== 显示修改配送单弹窗 ===')
  console.log('配送单数据:', order)
  console.log('已有容器码:', order.containerCodes)
  
  // 加载已被其他配送单使用的容器码列表
  await loadUsedContainerCodes(order.id || order.orderNumber || '')
  
  // 初始化容器选择状态 - 预设已有的容器
  modifyContainerSelection.value = {
    destination: order.destination || '',
    containers: [], // 将通过 initialContainers 属性来设置
    container: ''
  }
  
  // 初始化容器码选择状态
  if (order.containerCodes && Array.isArray(order.containerCodes)) {
    selectedContainerCodes.value = [...order.containerCodes]  // 初始时全部选中
    removedContainerCodes.value = []  // 清空取消选择列表
  } else {
    selectedContainerCodes.value = []
    removedContainerCodes.value = []
  }
  
  // 清空错误信息
  modifyFormErrors.value = {
    container: ''
  }
  
  showModifyDelivery.value = true
  
  console.log('修改配送单弹窗已打开，初始容器选择状态:', modifyContainerSelection.value)
  console.log('初始选中的容器码:', selectedContainerCodes.value)
}

function closeModifyModal() {
  showModifyDelivery.value = false
  currentModifyOrder.value = null
  
  // 重置容器选择状态
  modifyContainerSelection.value = {
    destination: '',
    containers: [],
    container: ''
  }
  
  // 重置容器码选择状态
  selectedContainerCodes.value = []
  removedContainerCodes.value = []
  
  modifyFormErrors.value = {
    container: ''
  }
}

function handleModifyContainerSelected(eventData) {
  // 处理所有类型的容器事件：select、remove、clear、initialize
  if (!eventData.action) {
    return
  }
  
  console.log('=== 修改配送单的容器事件处理 ===')
  console.log('事件类型:', eventData.action)
  console.log('选中容器数量:', eventData.selectedContainers ? eventData.selectedContainers.length : 0)
  
  if (eventData.selectedContainers && Array.isArray(eventData.selectedContainers)) {
    modifyContainerSelection.value = {
      destination: modifyContainerSelection.value.destination,
      containers: eventData.selectedContainers,
      container: eventData.selectedContainers.length > 0 ? eventData.selectedContainers[0].id : ''
    }
    
    // 🔥 关键修改：同步更新selectedContainerCodes，确保包含通过ContainerFilter选择的容器
    // 获取通过ContainerFilter组件选择的容器码
    const newlySelectedContainerCodes = eventData.selectedContainers.map(container => {
      return getContainerCodeDisplay(container) || extractContainerCode(container)
    }).filter(code => code)
    
    // 合并原始选中的容器码和新选择的容器码
    // selectedContainerCodes包含: 原始容器码中未被移除的 + 新选择的容器码
    const allSelectedContainerCodes = [
      ...selectedContainerCodes.value, // 保留原始选中且未移除的容器码
      ...newlySelectedContainerCodes    // 添加新选择的容器码
    ]
    
    // 去重处理
    selectedContainerCodes.value = [...new Set(allSelectedContainerCodes)]
    
    console.log('已更新修改配送单的容器选择:', modifyContainerSelection.value)
    console.log('🔥 同步更新的所有容器码:', selectedContainerCodes.value)
    console.log('新增的容器码:', newlySelectedContainerCodes)
  } else {
    // 如果没有选中容器（比如清空操作），重置选择
    modifyContainerSelection.value = {
      destination: modifyContainerSelection.value.destination,
      containers: [],
      container: ''
    }
    
    // 🔥 清空操作时，只保留原始容器码中未被移除的部分
    if (eventData.action === 'clear') {
      // 重置为原始状态（当前修改订单的原始容器码减去已移除的）
      const originalContainerCodes = currentModifyOrder.value?.containerCodes || []
      selectedContainerCodes.value = originalContainerCodes.filter(
        code => !removedContainerCodes.value.includes(code)
      )
    }
    
    console.log('已清空修改配送单的容器选择')
    console.log('剩余的容器码:', selectedContainerCodes.value)
  }
}

// 容器码选择状态判断方法
function isContainerCodeSelected(containerCode) {
  return selectedContainerCodes.value.includes(containerCode)
}

function isContainerCodeDeselected(containerCode) {
  return removedContainerCodes.value.includes(containerCode)
}

// 切换容器码选择状态
function toggleContainerCodeSelection(containerCode) {
  const isCurrentlySelected = selectedContainerCodes.value.includes(containerCode)
  const isCurrentlyRemoved = removedContainerCodes.value.includes(containerCode)
  
  if (isCurrentlySelected) {
    // 从选中状态切换到取消选择状态
    selectedContainerCodes.value = selectedContainerCodes.value.filter(code => code !== containerCode)
    if (!isCurrentlyRemoved) {
      removedContainerCodes.value.push(containerCode)
    }
  } else {
    // 从取消选择状态切换到选中状态
    if (isCurrentlyRemoved) {
      removedContainerCodes.value = removedContainerCodes.value.filter(code => code !== containerCode)
    }
    selectedContainerCodes.value.push(containerCode)
  }
  
  console.log('切换容器码选择状态:', {
    containerCode,
    selectedContainerCodes: selectedContainerCodes.value,
    removedContainerCodes: removedContainerCodes.value
  })
}

async function updateDeliveryOrder() {
  // 验证容器选择 - 检查是否至少有一个选中的容器
  if (!selectedContainerCodes.value || selectedContainerCodes.value.length === 0) {
    modifyFormErrors.value.container = '请至少选择一个容器'
    return
  }
  
  updatingOrder.value = true
  
  try {
    // 🔥 增强：获取完整的容器信息用于调试和验证
    // 统一清洗容器码，去除多余转义/外层数组/引号
    const sanitizeCode = (code) => {
      if (code === undefined || code === null) return ''
      let c = String(code).trim()
      // 1) 尝试作为JSON数组解析（完整形如 ["RQ..."]）
      if (c.startsWith('[') && c.endsWith(']')) {
        try {
          const parsed = JSON.parse(c)
          if (Array.isArray(parsed) && parsed.length > 0) {
            c = String(parsed[0]).trim()
          }
        } catch (e) {
          // 忽略，继续执行正则清洗
        }
      }
      // 2) 兼容半格式：开头残留 [ 或 ["，结尾残留 "] 或 ]
      c = c.replace(/^\s*\[\s*/g, '')          // 去掉开头的[
      c = c.replace(/\s*\]\s*$/g, '')          // 去掉结尾的]
      c = c.replace(/^\s*\\*"/g, '')           // 去掉开头转义或普通引号
      c = c.replace(/\\*"\s*$/g, '')           // 去掉结尾转义或普通引号
      c = c.replace(/^\s*'+/g, '')               // 去掉开头单引号
      c = c.replace(/'+\s*$/g, '')               // 去掉结尾单引号
      // 3) 清理残留转义符
      c = c.replace(/\\/g, '')
      return c.trim()
    }

    const originalContainerCodesRaw = currentModifyOrder.value?.containerCodes || []
    const originalContainerCodes = originalContainerCodesRaw.map(sanitizeCode).filter(c => c)
    const finalContainerCodes = selectedContainerCodes.value.map(sanitizeCode).filter(c => c)
    const addedContainerCodes = finalContainerCodes.filter(code => !originalContainerCodes.includes(code))
    const keptContainerCodes = finalContainerCodes.filter(code => originalContainerCodes.includes(code))
    
    // 准备Webhook数据
    const updateData = {
      orderNumber: currentModifyOrder.value.orderNumber || currentModifyOrder.value.id,
      containerCodes: finalContainerCodes,  // 🔥 所有最终选中的容器码（原有+新增-移除）
      removedContainerCodes: removedContainerCodes.value.map(sanitizeCode).filter(c => c),  // 被移除的容器码
      addedContainerCodes: addedContainerCodes,  // 🔥 新增：新添加的容器码
      originalContainerCodes: originalContainerCodes,  // 🔥 新增：原始容器码（用于后端对比）
      containerSummary: {  // 🔥 新增：容器变更摘要
        total: finalContainerCodes.length,
        kept: keptContainerCodes.length,
        added: addedContainerCodes.length,
        removed: removedContainerCodes.value.length,
        keptCodes: keptContainerCodes,
        addedCodes: addedContainerCodes,
        removedCodes: removedContainerCodes.value
      },
      updatedAt: new Date().toISOString()
    }
    
    console.log('=== 发送配送单修改Webhook ===')
    console.log('📦 原始容器码:', originalContainerCodes)
    console.log('📦 最终容器码:', finalContainerCodes)
    console.log('➕ 新增容器码:', addedContainerCodes)
    console.log('➖ 移除容器码:', removedContainerCodes.value)
    console.log('✅ 保留容器码:', keptContainerCodes)
    console.log('🚀 完整修改数据:', updateData)
    
    // 获取Webhook地址（参考创建配送单的成功实现）
    console.log('=== 调试修改Webhook配置读取过程 ===');
    console.log('window.mdye存在:', !!window.mdye);
    console.log('window.mdye.env存在:', !!window.mdye?.env);
    console.log('window.mdye.env.config存在:', !!window.mdye?.env?.config);
    console.log('完整config对象:', window.mdye?.env?.config);
    
    const config = window.mdye?.env?.config || {};
    console.log('可用配置键:', Object.keys(config));
    console.log('MODIFY_WEBHOOK_URL原始值:', config.MODIFY_WEBHOOK_URL);
    console.log('webhookUrl原始值:', config.webhookUrl);
    console.log('modifyWebhookUrl原始值:', config.modifyWebhookUrl);
    
    // 使用配置系统读取webhook地址
    const webhookUrlFromConfig = WEBHOOKS.MODIFY;
    console.log('通过WEBHOOKS.MODIFY获取:', webhookUrlFromConfig);
    
    // 备用方案：直接从config读取
    const webhookUrlDirect = config.MODIFY_WEBHOOK_URL || 
                             config.webhookUrl || 
                             config.modifyWebhookUrl;
    console.log('直接从config获取:', webhookUrlDirect);
    
    const webhookUrl = webhookUrlFromConfig || webhookUrlDirect;
    console.log('最终获取的修改Webhook URL:', webhookUrl);
    
    if (!webhookUrl) {
      console.error('❌ 未配置修改webhook地址');
      console.log('📋 请在明道云插件中添加以下任一参数:');
      console.log('   - MODIFY_WEBHOOK_URL: 配送单修改专用webhook地址');
      console.log('   - webhookUrl: 通用webhook地址');
      console.log('   - modifyWebhookUrl: 修改webhook地址');
      
      alert('未配置修改webhook地址，请在明道云插件中添加 MODIFY_WEBHOOK_URL 或 webhookUrl 参数');
      return;
    }
    
    // 调用修改配送单的webhook
    try {
      const response = await fetch(webhookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updateData)
      });
      
      console.log('=== 修改Webhook响应 ===');
      console.log('响应状态:', response.status);
      console.log('响应状态文本:', response.statusText);
      
      let responseData = null;
      try {
        responseData = await response.text();
        console.log('响应内容:', responseData);
        
        if (responseData) {
          try {
            responseData = JSON.parse(responseData);
          } catch (e) {
            // 保持原始文本
          }
        }
      } catch (e) {
        console.log('无响应内容或解析失败');
      }
      
      if (!response.ok) {
        console.warn('⚠️ 修改Webhook发送失败');
        throw new Error(`修改Webhook发送失败: ${response.status} ${response.statusText}`);
      }
      
      console.log('✅ 配送单修改Webhook发送成功');
      alert('配送单修改成功！');
      
      // 关闭弹窗
      closeModifyModal();
      
      // 刷新配送单列表
      setTimeout(async () => {
        await loadDeliveryOrders();
      }, 1000);
      
    } catch (webhookError) {
      console.error('❌ 修改Webhook发送异常:', webhookError);
      throw new Error(`修改Webhook发送异常: ${webhookError.message}`);
    }
    
  } catch (err) {
    console.error('❌ 修改配送单失败:', err)
    alert(`修改配送单失败: ${err.message}`)
  } finally {
    updatingOrder.value = false
  }
}

// 订单操作
function viewOrderDetail(order) {
  // 这里可以添加订单详情页面
}

// 检查订单是否已发运的工具函数
function isOrderShipped(order) {
  if (!order || !order.status) {
    return false
  }
  
  const status = String(order.status).trim()
  
  // 检查是否为"已发运"状态的各种可能表达方式
  const shippedPatterns = [
    '已发运',
    '发运完成', 
    '已配送',
    '配送完成',
    '已出发',
    'shipped',
    'completed',
    'delivered'
  ]
  
  const isShipped = shippedPatterns.some(pattern => 
    status.toLowerCase().includes(pattern.toLowerCase())
  )
  
  return isShipped
}

function processOrder(order) {
  // 检查订单是否已经发运
  if (isOrderShipped(order)) {
    return
  }
  
  // 只有未发运的订单才能进行发运确认
  if (!isOrderShipped(order)) {
    confirmTitle.value = '确认发运'
    confirmMessage.value = `确认发运配送单号 ${order.orderNumber || order.id} 吗？`
    confirmType.value = 'confirmDelivery'
    confirmData.value = order
    showConfirmModal.value = true
  }
}

async function confirmAction() {
  if (confirmType.value === 'confirmDelivery') {
    try {
      // 准备发运确认的webhook数据
      const confirmDeliveryData = {
        orderNumber: confirmData.value.orderNumber || confirmData.value.id,
        orderId: confirmData.value.id,
        status: 'completed',
        confirmedAt: new Date().toISOString(),
        containerCodes: confirmData.value.containerCodes || [],
        deliveryMethod: confirmData.value.deliveryMethod || confirmData.value.method,
        destination: confirmData.value.destination,
        driverName: confirmData.value.driverName,
        vehicleInfo: confirmData.value.vehicleInfo
      }
      
      console.log('=== 发送确认发运Webhook ===')
      console.log('发运确认数据:', confirmDeliveryData)
      
      // 获取确认发运Webhook地址（参考修改配送单的成功实现）
      console.log('=== 调试确认发运Webhook配置读取过程 ===');
      console.log('window.mdye存在:', !!window.mdye);
      console.log('window.mdye.env存在:', !!window.mdye?.env);
      console.log('window.mdye.env.config存在:', !!window.mdye?.env?.config);
      console.log('完整config对象:', window.mdye?.env?.config);
      
      const config = window.mdye?.env?.config || {};
      console.log('可用配置键:', Object.keys(config));
      console.log('CONFIRM_WEBHOOK_URL原始值:', config.CONFIRM_WEBHOOK_URL);
      console.log('webhookUrl原始值:', config.webhookUrl);
      console.log('confirmWebhookUrl原始值:', config.confirmWebhookUrl);
      
      // 使用配置系统读取webhook地址
      const webhookUrlFromConfig = WEBHOOKS.CONFIRM;
      console.log('通过WEBHOOKS.CONFIRM获取:', webhookUrlFromConfig);
      
      // 备用方案：直接从config读取
      const webhookUrlDirect = config.CONFIRM_WEBHOOK_URL || 
                               config.webhookUrl || 
                               config.confirmWebhookUrl;
      console.log('直接从config获取:', webhookUrlDirect);
      
      const webhookUrl = webhookUrlFromConfig || webhookUrlDirect;
      console.log('最终获取的确认发运Webhook URL:', webhookUrl);
      
      if (!webhookUrl) {
        console.error('❌ 未配置确认发运webhook地址');
        console.log('📋 请在明道云插件中添加以下任一参数:');
        console.log('   - CONFIRM_WEBHOOK_URL: 确认发运专用webhook地址');
        console.log('   - webhookUrl: 通用webhook地址');
        console.log('   - confirmWebhookUrl: 确认发运webhook地址');
        
        alert('未配置确认发运webhook地址，请在明道云插件中添加 CONFIRM_WEBHOOK_URL 或 webhookUrl 参数');
        return;
      }
      
      // 调用确认发运的webhook
      try {
        const response = await fetch(webhookUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(confirmDeliveryData)
        });
        
        console.log('=== 确认发运Webhook响应 ===');
        console.log('响应状态:', response.status);
        console.log('响应状态文本:', response.statusText);
        
        let responseData = null;
        try {
          responseData = await response.text();
          console.log('响应内容:', responseData);
          
          if (responseData) {
            try {
              responseData = JSON.parse(responseData);
            } catch (e) {
              // 保持原始文本
            }
          }
        } catch (e) {
          console.log('无响应内容或解析失败');
        }
        
        if (!response.ok) {
          console.warn('⚠️ 确认发运Webhook发送失败');
          throw new Error(`确认发运Webhook发送失败: ${response.status} ${response.statusText}`);
        }
        
        console.log('✅ 确认发运Webhook发送成功');
        
        // 更新本地状态
        confirmData.value.status = 'completed';
        
        const orderIndex = deliveryOrders.value.findIndex(o => o.id === confirmData.value.id);
        if (orderIndex !== -1) {
          deliveryOrders.value[orderIndex].status = 'completed';
        }
        
        // 同步更新显示订单列表
        const displayOrderIndex = displayOrders.value.findIndex(o => o.id === confirmData.value.id);
        if (displayOrderIndex !== -1) {
          displayOrders.value[displayOrderIndex].status = 'completed';
        }
        
        alert('发运确认成功！');
        
      } catch (webhookError) {
        console.error('❌ 确认发运Webhook发送异常:', webhookError);
        throw new Error(`确认发运Webhook发送异常: ${webhookError.message}`);
      }
      
    } catch (error) {
      console.error('确认发运失败:', error)
      alert(`确认发运失败: ${error.message}`)
    }
  }
  
  closeConfirmModal()
}

// 筛选相关
function toggleFilterPanel() {
  showFilterPanel.value = !showFilterPanel.value
}

function applyFilters() {
}

function clearFilters() {
  filters.value = {
    deliveryMethod: '',
    status: ''
  }
}

function getActiveFilterCount() {
  let count = 0
  if (filters.value.deliveryMethod) count++
  if (filters.value.status) count++
  return count
}

// 状态相关
function getStatusText(status) {
  if (!status) return '未知状态'
  
  // 直接返回从API获取的状态文本，如果是已知的英文状态则翻译
  const statusMap = {
    'pending': '待处理',
    'in_progress': '配送中', 
    'completed': '已完成',
    'cancelled': '已取消',
    'shipped': '已发运'
  }
  
  // 如果是已知的英文状态码，返回中文翻译
  if (statusMap[status]) {
    return statusMap[status]
  }
  
  // 否则直接返回原始状态文本（通常已经是中文）
  return String(status)
}

function getStatusClass(status) {
  if (!status) return 'status-unknown'
  
  const statusStr = String(status).toLowerCase()
  
  // 检查各种状态模式
  if (statusStr.includes('已发运') || statusStr.includes('shipped') || statusStr.includes('发运完成')) {
    return 'status-shipped'
  }
  
  if (statusStr.includes('已完成') || statusStr.includes('completed') || statusStr.includes('配送完成')) {
    return 'status-completed' 
  }
  
  if (statusStr.includes('配送中') || statusStr.includes('in_progress') || statusStr.includes('进行中')) {
    return 'status-progress'
  }
  
  if (statusStr.includes('待处理') || statusStr.includes('pending') || statusStr.includes('未处理')) {
    return 'status-pending'
  }
  
  if (statusStr.includes('已取消') || statusStr.includes('cancelled') || statusStr.includes('取消')) {
    return 'status-cancelled'
  }
  
  return 'status-unknown'
}

// 工具函数
function formatDate(dateString) {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return dateString
  }
}

// 导航相关
function backToMain() {
  currentView.value = 'main'
  error.value = ''
}

// 弹窗控制
function closeCreateModal() {
  showCreateDelivery.value = false
  // 重置表单
  newDelivery.value = {
    method: '',
    destination: '',
    driver: '',
    vehicle: '',
    container: '',
  }
  // 重置容器筛选
  containerSelection.value = {
    destination: '',
    containers: [],
    container: ''
  }
  
  formErrors.value = {
    method: '',
    destination: '',
    driver: '',
    vehicle: '',
    container: ''
  }
}

// 处理容器选择事件
function handleContainerSelected(eventData) {
  
  // 处理所有类型的容器事件：select、remove、clear、initialize
  if (!eventData.action) {
    console.warn('容器事件缺少action字段')
    return
  }
  
  console.log('=== 创建配送单的容器事件处理 ===')
  console.log('事件类型:', eventData.action)
  console.log('选中容器数量:', eventData.selectedContainers ? eventData.selectedContainers.length : 0)
  
  if (eventData.selectedContainers && Array.isArray(eventData.selectedContainers)) {
    
    // 更新容器选择状态（保留兼容性）
    containerSelection.value = {
      destination: containerSelection.value.destination,
      containers: eventData.selectedContainers,
      container: eventData.selectedContainers.length > 0 ? eventData.selectedContainers[0].id : ''
    }
    
    console.log('已更新创建配送单的容器选择:', containerSelection.value)
    
    // 日志记录容器码信息
    eventData.selectedContainers.forEach((container, index) => {
      const containerCode = extractContainerCode(container)
      // 容器码已提取
    })
  } else {
    // 如果没有选中容器（比如清空操作），重置选择
    containerSelection.value = {
      destination: containerSelection.value.destination,
      containers: [],
      container: ''
    }
    
    console.log('已清空创建配送单的容器选择')
  }
}

// 提取容器码的通用函数
function extractContainerCode(container) {
  if (!container) {
    console.warn('容器对象为空')
    return `UNKNOWN_${Date.now()}`
  }
  
  
  let containerCode = ''
  
  // 方法1: 从 rawData 中获取
  if (container.rawData) {
    containerCode = container.rawData[CONTAINER_FIELDS.CONTAINER_CODE] || 
                   container.rawData.containerCode || 
                   container.rawData.code || ''
    if (containerCode) {
      // 检查是否是JSON字符串数组
      if (typeof containerCode === 'string' && containerCode.startsWith('[') && containerCode.endsWith(']')) {
        try {
          const parsed = JSON.parse(containerCode)
          if (Array.isArray(parsed) && parsed.length > 0) {
            return String(parsed[0]).trim()
          }
        } catch (e) {
          // 继续使用原始字符串
        }
      }
      return containerCode
    }
  }
  
  // 方法2: 从容器对象直接获取
  containerCode = container[CONTAINER_FIELDS.CONTAINER_CODE] || 
                 container.containerCode || 
                 container.code || ''
  if (containerCode) {
    // 检查是否是JSON字符串数组
    if (typeof containerCode === 'string' && containerCode.startsWith('[') && containerCode.endsWith(']')) {
      try {
        const parsed = JSON.parse(containerCode)
        if (Array.isArray(parsed) && parsed.length > 0) {
          return String(parsed[0]).trim()
        }
      } catch (e) {
        // 继续使用原始字符串
      }
    }
    return containerCode
  }
  
  // 方法3: 使用容器ID作为备用方案
  const fallbackCode = container.id || container.rowid || `CONTAINER_${Date.now()}`
  console.warn(`未找到容器码，使用备用方案: ${fallbackCode}`)
  return fallbackCode
}

function closeContainerModal() {
  showContainerSelection.value = false
  selectedContainer.value = null
}

function closeConfirmModal() {
  showConfirmModal.value = false
  confirmTitle.value = ''
  confirmMessage.value = ''
  confirmType.value = ''
  confirmData.value = null
}

// 重试操作
function retryCurrentOperation() {
  error.value = ''
  if (currentView.value === 'orders') {
    loadDeliveryOrders()
  } else if (currentView.value === 'containers') {
    loadContainers()
  } else {
    loadDeliveryOrders()
  }
}

// 辅助函数 - 获取司机名称
function getDriverName(driverId) {
  const driver = drivers.value.find(d => d.id === driverId)
  return driver ? driver.name : '未知司机'
}

// 辅助函数 - 获取车辆信息（优先显示车牌号）
function getVehicleName(vehicleId) {
  const vehicle = vehicles.value.find(v => v.id === vehicleId)
  return vehicle ? vehicle.displayText : '未知车辆'
}

// 移动端展开/折叠相关方法
function toggleOrderExpansion(orderId) {
  expandedOrdersMap.value[orderId] = !expandedOrdersMap.value[orderId]
}

function isOrderExpanded(orderId) {
  return !!expandedOrdersMap.value[orderId]
}

// 获取容器码显示
function getContainerCodeDisplay(container) {
  console.log('=== 获取容器码显示 - 调试信息 ===')
  console.log('容器对象:', container)
  
  if (!container) {
    console.log('容器对象为空')
    return '未知容器'
  }
  
  let containerCode = ''
  
  // 方法1: 从rawData中获取容器码
  if (container.rawData && typeof container.rawData === 'object') {
    // 尝试多个可能的字段
    containerCode = container.rawData[CONTAINER_FIELDS.CONTAINER_CODE] || // 明道云容器码字段ID
                   container.rawData[CONTAINER_FIELDS.CONTAINER_CODE] || // 另一个可能的容器码字段ID
                   container.rawData.containerCode || 
                   container.rawData.code || 
                   container.rawData.name || ''
    
    if (containerCode) {
      console.log('从rawData获取的容器码:', containerCode)
      // 检查是否是JSON字符串数组
      if (typeof containerCode === 'string' && containerCode.startsWith('[' ) && containerCode.endsWith(']')) {
        try {
          const parsed = JSON.parse(containerCode)
          if (Array.isArray(parsed) && parsed.length > 0) {
            // 如果是数组，返回第一个元素
            console.log('解析JSON数组，提取第一个元素:', parsed[0])
            return String(parsed[0]).trim()
          }
        } catch (e) {
          console.log('JSON解析失败，使用原始字符串')
        }
      }
      return String(containerCode).trim()
    }
  }
  
  // 方法2: 直接从容器对象获取
  containerCode = container[CONTAINER_FIELDS.CONTAINER_CODE] || // 明道云容器码字段ID
                 container[CONTAINER_FIELDS.CONTAINER_CODE] || // 另一个可能的容器码字段ID
                 container.containerCode || 
                 container.code || 
                 container.name || ''
  
  if (containerCode) {
    console.log('从容器对象直接获取的容器码:', containerCode)
    // 检查是否是JSON字符串数组
    if (typeof containerCode === 'string' && containerCode.startsWith('[' ) && containerCode.endsWith(']')) {
      try {
        const parsed = JSON.parse(containerCode)
        if (Array.isArray(parsed) && parsed.length > 0) {
          // 如果是数组，返回第一个元素
          console.log('解析JSON数组，提取第一个元素:', parsed[0])
          return String(parsed[0]).trim()
        }
      } catch (e) {
        console.log('JSON解析失败，使用原始字符串')
      }
    }
    return String(containerCode).trim()
  }
  
  // 方法3: 检查是否有products字段，从中提取容器编号
  if (container.products && typeof container.products === 'string') {
    // 尝试从商品信息中提取容器编号（如果有的话）
    const productText = container.products
    const codeMatch = productText.match(/容器[编号码]?[:：]?\s*([A-Za-z0-9\-]+)/)
    if (codeMatch) {
      console.log('从商品信息中提取的容器码:', codeMatch[1])
      return codeMatch[1].trim()
    }
  }
  
  console.log('=== 容器码获取失败，使用备用方案 ===')
  console.log('container.id:', container.id)
  console.log('container.rowid:', container.rowid)
  
  // 最后备用方案：生成一个更友好的显示名称
  if (container.id && container.id.length > 8) {
    // 如果ID是长哈希，显示简化版本
    const shortId = container.id.substring(0, 8).toUpperCase()
    console.log('生成简化容器码:', `CT-${shortId}`)
    return `CT-${shortId}`
  }
  
  return container.id || container.rowid || '未知容器'
}

// 获取容器配送站点信息
function getContainerSiteInfo(container) {
  if (!container) {
    return ''
  }
  
  // 尝试从rawData中获取配送站点信息
  if (container.rawData) {
    const siteInfo = container.rawData[CONTAINER_FIELDS.CONTAINER_SITE_INFO] || // 配送站点信息字段ID
                    container.rawData.siteInfo || 
                    container.rawData.site || ''
    if (siteInfo) {
      return String(siteInfo).trim()
    }
  }
  
  // 尝试从容器对象直接获取
  const siteInfo = container[CONTAINER_FIELDS.CONTAINER_SITE_INFO] || 
                  container.siteInfo || 
                  container.site || ''
  if (siteInfo) {
    return String(siteInfo).trim()
  }
  
  return ''
}

// 检查是否有容器码数据
function hasContainerCodes(order) {
  // 检查是否有容器码数组数据
  if (order.containerCodes && Array.isArray(order.containerCodes) && order.containerCodes.length > 0) {
    return true;
  }
  
  // 检查rawData中是否有拥有容器字段数据（新的字段ID）
  if (order.rawData && order.rawData['68abf59bd237ea76ea821c8f']) {
    return true;
  }
  
  // 检查是否有容器数量数据作为备用
  if (order.containerCount && order.containerCount > 0) {
    return true;
  }
  
  return false;
}

// 获取容器码显示
function getContainerCodesDisplay(order) {
  // 方案1：使用处理过的containerCodes数组
  if (order.containerCodes && Array.isArray(order.containerCodes) && order.containerCodes.length > 0) {
    return order.containerCodes.join(',');
  }
  
  // 方案2：从rawData中获取拥有容器字段（新的字段ID）
  if (order.rawData && order.rawData['68abf59bd237ea76ea821c8f']) {
    const rawValue = order.rawData['68abf59bd237ea76ea821c8f'];
    let processedValue = String(rawValue);
    
    // 移除JSON格式的大括号 { 和 }
    processedValue = processedValue.replace(/[{}]/g, '');
    
    // 如果包含引号和冒号，可能是JSON格式，进一步处理
    if (processedValue.includes('"') && processedValue.includes(':')) {
      // 尝试提取值部分
      processedValue = processedValue.replace(/[":]/g, '').trim();
    }
    
    return processedValue;
  }
  
  // 方案3：临时显示：如果有容器数量，就显示容器数量信息
  if (order.containerCount && order.containerCount > 0) {
    return `${order.containerCount}个容器（容器码待同步）`;
  }
  
  return '暂无数据';
}

// 容器状态检查函数
function getContainerStatus(container) {
  if (!container) {
    console.log('getContainerStatus: 容器对象为空')
    return ''
  }
  
  // 使用容器状态字段ID
  const statusFieldId = '6889ccc302274fada36ece1c'
  
  let containerStatus = ''
  
  // 从rawData中获取
  if (container.rawData && container.rawData[statusFieldId]) {
    containerStatus = container.rawData[statusFieldId]
    console.log(`从rawData获取状态: "${containerStatus}"`)
  }
  
  // 直接从容器对象获取
  if (!containerStatus && container[statusFieldId]) {
    containerStatus = container[statusFieldId]
    console.log(`从容器对象直接获取状态: "${containerStatus}"`)
  }
  
  if (!containerStatus) {
    console.log('未找到状态字段，可用字段:', container.rawData ? Object.keys(container.rawData) : '无rawData', container ? Object.keys(container) : '无容器数据')
  }
  
  return containerStatus || ''
}

function isContainerStatusInUse(status) {
  if (!status) return false
  
  const statusStr = String(status).trim().toLowerCase()
  
  // 首先排除"待使用"状态
  if (statusStr.includes('待使用') || statusStr.includes('待') || statusStr === 'pending' || statusStr === 'waiting') {
    console.log(`容器状态"${status}"为待使用状态，已排除`)
    return false
  }
  
  // 只检查是否为"使用中"状态
  const inUsePatterns = [
    '使用中',
    '使用',
    '在用',
    '已使用',
    'in_use',
    'in use',
    'using',
    'active',
    'occupied'
  ]
  
  const isMatch = inUsePatterns.some(pattern => 
    statusStr.includes(pattern.toLowerCase())
  )
  
  // 调试信息：显示状态筛选结果
  if (!isMatch && status) {
    console.log(`容器状态"${status}"不符合"使用中"筛选条件`)
  }
  
  return isMatch
}

// 删除了复杂的容器详情计算函数，改为直接使用明道云汇总字段
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.delivery-app {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.main-header {
  background: linear-gradient(135deg, #f8b300 0%, #f39c12 100%);
  padding: 1.5rem;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 4px 15px rgba(248, 179, 0, 0.3);
  position: relative;
  overflow: hidden;
}

.main-header::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  animation: shimmer 3s ease-in-out infinite;
}

@keyframes shimmer {
  0%, 100% { transform: translate(-50%, -50%) rotate(0deg); }
  50% { transform: translate(-50%, -50%) rotate(180deg); }
}

.header-actions {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.new-delivery-btn, .container-manage-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  cursor: pointer;
  font-size: 0.95rem;
  font-weight: 500;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.new-delivery-btn:hover, .container-manage-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

.btn-icon {
  font-size: 1.2rem;
  font-weight: bold;
}

.filter-controls {
  padding: 1rem;
  background: white;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: flex-end;
}

.main-header h1 {
  margin: 0;
  font-weight: 600;
  font-size: 1.8rem;
}

.back-btn, .refresh-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.2s;
}

.back-btn:hover, .refresh-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.loading, .error-message {
  text-align: center;
  padding: 2rem;
  margin: 1rem;
  border-radius: 8px;
}

.loading {
  background: #f8f9fa;
  color: #666;
}

.error-message {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.retry-btn {
  background: #dc3545;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 1rem;
  transition: background-color 0.2s;
}

.retry-btn:hover {
  background: #c82333;
}


/* 容器模态框特定样式 */
.container-modal {
  max-height: 80vh;
  overflow-y: auto;
}

.container-modal-actions {
  margin-bottom: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-info {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.filter-badge {
  background: #17a2b8;
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
}

.container-count {
  color: #666;
  font-size: 0.85rem;
}

.container-modal-actions .refresh-btn {
  background: #17a2b8;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.container-modal-actions .refresh-btn:hover {
  background: #138496;
}

/* 容器筛选组件样式 */
.container-filter-section {
  margin: 1rem 0;
}

/* 容器选择区域样式 */
.container-selection-section {
  margin: 1.5rem 0;
  padding: 1rem 0;
  border-top: 1px solid #e9ecef;
  border-bottom: 1px solid #e9ecef;
}

.container-error {
  margin-top: 0.5rem;
  text-align: center;
  font-weight: 500;
}

/* 主内容区域 */
.delivery-main {
  min-height: 100vh;
  background: transparent;
}

.order-items {
  padding: 1rem;
  max-height: calc(100vh - 250px);
  overflow-y: auto;
}

.container-items {
  padding: 0;
  max-height: 50vh;
  overflow-y: auto;
}

.order-item, .container-item {
  background: white;
  border-radius: 12px;
  padding: 1.5rem;
  margin-bottom: 1rem;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  border-left: 4px solid transparent;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  min-height: 180px;
}

.order-item::before, .container-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #f8b300, #e67e22, #f8b300);
  transform: translateX(-100%);
  transition: transform 0.3s ease;
}

.order-item:hover, .container-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  border-left-color: #f8b300;
}

.order-item:hover::before, .container-item:hover::before {
  transform: translateX(0);
}

.order-info, .container-info {
  flex: 1;
}

.order-number, .container-id {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 0.75rem;
}

.container-site {
  display: flex;
  align-items: center;
  margin-bottom: 0.75rem;
  padding: 0.5rem;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #17a2b8;
}

.container-site strong {
  color: #17a2b8;
  margin-right: 0.5rem;
  font-weight: 600;
  font-size: 0.9rem;
}

.container-site .site-info {
  color: #333;
  font-weight: 500;
  font-size: 0.95rem;
  background: white;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.destination-display {
  display: flex;
  align-items: center;
  margin-bottom: 2px;
  padding: 4px 0;
}

.destination-label {
  color: #555;
  font-weight: 600;
  margin-right: 0.5rem;
  font-size: 0.85rem;
  text-transform: uppercase;
  letter-spacing: 0.3px;
  opacity: 0.8;
  min-width: 75px;
}

.destination-label::after {
  content: ':';
  margin-left: 2px;
  font-weight: 400;
  opacity: 0.6;
}

.destination-value {
  color: #222;
  font-weight: 500;
  flex: 1;
  font-size: 0.9rem;
  background: white;
  padding: 6px 10px;
  border-radius: 6px;
  border: 1px solid transparent;
  box-shadow: none;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.order-meta {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(auto, minmax(auto, 1fr));
  gap: 0.25rem 0.75rem;
  margin-bottom: 0.75rem;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 0.9rem;
  padding: 4px 0;
  margin: 2px 0;
  transition: all 0.2s ease;
}

.meta-item:hover {
  background: rgba(248, 179, 0, 0.03);
  transform: translateX(1px);
}

.meta-label {
  color: #555;
  font-weight: 600;
  margin-right: 0.25rem;
  min-width: 50px;
  font-size: 0.85rem;
  text-transform: uppercase;
  letter-spacing: 0.3px;
  opacity: 0.8;
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.meta-label::after {
  content: ':';
  margin-left: 2px;
  font-weight: 400;
  opacity: 0.6;
}

.meta-value {
  color: #222;
  font-weight: 500;
  flex: 1;
  font-size: 0.9rem;
  background: white;
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid transparent;
  box-shadow: none;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: 0;
}

.meta-value.status {
  padding: 6px 12px;
  border-radius: 12px;
  font-size: 0.85rem;
  font-weight: 600;
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 容器码标签样式 */
.meta-item.full-width {
  grid-column: 1 / -1;
}

.meta-value.container-codes {
  display: flex;
  flex-wrap: wrap;
  gap: 0.3rem;
  align-items: flex-start;
}

.container-code-tag {
  background: linear-gradient(135deg, #f8b300 0%, #e6a200 100%);
  color: white;
  padding: 4px 10px;
  border-radius: 10px;
  font-size: 0.8rem;
  font-weight: 600;
  white-space: nowrap;
  box-shadow: 0 3px 8px rgba(248, 179, 0, 0.4);
  border: 1px solid rgba(248, 179, 0, 0.5);
  transition: all 0.2s ease;
}

.container-code-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(248, 179, 0, 0.5);
}

.separator {
  display: none;
}

.status-pending {
  background: #fff3cd;
  color: #856404;
}

.status-progress {
  background: #d1ecf1;
  color: #0c5460;
}

.status-completed {
  background: #d4edda;
  color: #155724;
}

.status-cancelled {
  background: #f8d7da;
  color: #721c24;
}

.status-shipped {
  background: #d4edda;
  color: #155724;
  font-weight: 600;
}

.status-unknown {
  background: #e2e3e5;
  color: #383d41;
}

.destination-info {
  color: #666;
  font-size: 0.9rem;
}

.order-actions {
  margin-left: 1rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0.5rem;
  gap: 0.5rem;
  flex-shrink: 0;
}

.action-btn {
  background: linear-gradient(135deg, #f8b300 0%, #e6a200 100%);
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 10px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s ease;
  min-width: 120px;
  box-shadow: 0 3px 10px rgba(248, 179, 0, 0.3);
  position: relative;
  overflow: hidden;
}

.action-btn::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.3s ease, height 0.3s ease;
}

.action-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #e6a200 0%, #d49200 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(248, 179, 0, 0.4);
}

.action-btn:hover:not(:disabled)::before {
  width: 100%;
  height: 100%;
}

.action-btn:disabled {
  background: #e9ecef;
  color: #6c757d;
  cursor: not-allowed;
  transform: none;
}

/* 修改按钮特殊样式 */
.action-btn.modify-btn {
  background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
  box-shadow: 0 3px 10px rgba(23, 162, 184, 0.3);
}

.action-btn.modify-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #138496 0%, #117a8b 100%);
  box-shadow: 0 6px 20px rgba(23, 162, 184, 0.4);
}

/* 已发运状态的按钮样式 */
.action-btn.shipped {
  background: #28a745 !important;
  color: white !important;
  cursor: not-allowed;
  opacity: 0.8;
}

.action-btn.shipped:hover {
  transform: none;
}

/* 容器相关 */
.container-products {
  margin-top: 0.5rem;
}

.product-detail {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 0.75rem;
  margin-top: 0.5rem;
  font-size: 0.9rem;
  color: #666;
}

.no-products {
  color: #999;
  font-style: italic;
  margin-top: 0.5rem;
}

.selectable-container {
  border: 2px solid #e9ecef;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.selectable-container:hover {
  border-color: #f8b300;
}

.selectable-container.selected {
  border-color: #f8b300;
  background-color: rgba(248, 179, 0, 0.1);
}

/* 筛选面板 */
.filter-toggle-btn {
  background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
  color: white;
  border: none;
  padding: 0.75rem 1.25rem;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  position: relative;
  margin-left: auto;
  box-shadow: 0 2px 8px rgba(23, 162, 184, 0.3);
}

.filter-toggle-btn:hover {
  background: linear-gradient(135deg, #138496 0%, #117a8b 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(23, 162, 184, 0.4);
}

.filter-count {
  background: #dc3545;
  color: white;
  border-radius: 50%;
  padding: 0.2rem 0.4rem;
  font-size: 0.7rem;
  margin-left: 0.5rem;
}

.filter-panel {
  background: white;
  border: 1px solid rgba(248, 179, 0, 0.2);
  border-radius: 12px;
  padding: 1.5rem;
  margin: 1rem;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
}

.filter-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
  margin-bottom: 1rem;
}

.filter-item {
  display: flex;
  flex-direction: column;
}

.filter-item label {
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
  font-size: 0.9rem;
}

.filter-item select {
  padding: 0.6rem;
  border: 1px solid #ced4da;
  border-radius: 6px;
  font-size: 0.9rem;
  background: white;
  transition: border-color 0.2s;
}

.filter-item select:focus {
  outline: none;
  border-color: #17a2b8;
  box-shadow: 0 0 0 0.2rem rgba(23, 162, 184, 0.25);
}

.filter-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.clear-filters-btn, .close-filter-btn {
  padding: 0.6rem 1.2rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.clear-filters-btn {
  background: #dc3545;
  color: white;
}

.clear-filters-btn:hover {
  background: #c82333;
}

.close-filter-btn {
  background: #6c757d;
  color: white;
}

.close-filter-btn:hover {
  background: #5a6268;
}

/* 修改配送单弹窗样式 */
.modify-order-info {
  margin-bottom: 1.5rem;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #17a2b8;
}

.order-basic-info {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.order-basic-info > div {
  font-size: 0.9rem;
  color: #333;
}

.order-basic-info strong {
  color: #17a2b8;
  margin-right: 0.5rem;
}

/* 已选择的容器维度样式 */
.selected-containers-dimension {
  background: #fff;
  border: 2px solid #e3f2fd;
  border-radius: 12px;
  padding: 1.5rem;
  margin-bottom: 1.5rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.dimension-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1rem;
}

.dimension-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 0;
  font-size: 1.1rem;
  font-weight: 600;
  color: #1976d2;
}

.dimension-title .icon {
  font-size: 1.2rem;
}

.container-count-badge {
  background: #1976d2;
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 600;
}

.container-codes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 0.75rem;
}

.container-code-item {
  background: linear-gradient(135deg, #f8b300, #ffd54f);
  border: 2px solid rgba(248, 179, 0, 0.3);
  border-radius: 8px;
  padding: 0.75rem 1rem;
  text-align: center;
  transition: all 0.2s ease;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.5rem;
}

.container-code-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(248, 179, 0, 0.3);
}

/* 选中状态样式 */
.container-code-item.selected {
  background: linear-gradient(135deg, #4caf50, #81c784);
  border-color: #4caf50;
}

.container-code-item.selected:hover {
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}

/* 取消选择状态样式 */
.container-code-item.deselected {
  background: linear-gradient(135deg, #f44336, #ef5350);
  border-color: #f44336;
  opacity: 0.8;
}

.container-code-item.deselected:hover {
  box-shadow: 0 4px 12px rgba(244, 67, 54, 0.3);
}

.container-code-item .container-code {
  font-family: 'Courier New', monospace;
  font-weight: 600;
  font-size: 0.9rem;
  color: #333;
  letter-spacing: 0.5px;
  flex-grow: 1;
}

.selection-status {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 20px;
}

.status-icon {
  font-weight: bold;
  font-size: 1rem;
  display: inline-block;
}

.status-icon.selected {
  color: #fff;
}

.status-icon.deselected {
  color: #fff;
}

.status-icon.neutral {
  color: rgba(51, 51, 51, 0.6);
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 16px;
  padding: 2rem;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 25px 80px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.modal-content.large {
  max-width: 700px;
  max-height: 85vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #e9ecef;
}

.modal-header h3 {
  color: #333;
  font-size: 1.3rem;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background: #f8f9fa;
}

/* 表单样式 */
.delivery-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-label {
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
  font-size: 0.9rem;
}

.form-control {
  padding: 0.75rem;
  border: 1px solid #ced4da;
  border-radius: 6px;
  font-size: 0.9rem;
  transition: border-color 0.2s;
}

.form-control:focus {
  outline: none;
  border-color: #f8b300;
  box-shadow: 0 0 0 0.2rem rgba(248, 179, 0, 0.25);
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.error {
  color: #dc3545;
  font-size: 0.8rem;
  margin-top: 0.25rem;
}

.form-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #e9ecef;
}

.modal-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 2rem;
}

.cancel-btn, .confirm-btn, .submit-btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f8f9fa;
  color: #333;
  border: 1px solid #ddd;
}

.cancel-btn:hover {
  background: #e9ecef;
}

.confirm-btn, .submit-btn {
  background: #f8b300;
  color: white;
}

.confirm-btn:hover, .submit-btn:hover:not(:disabled) {
  background: #e6a200;
}

.submit-btn:disabled, .confirm-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.container-selection {
  max-height: 400px;
  overflow-y: auto;
}

/* PC端展开/折叠按钮容器 */
.toggle-btn-container.pc-toggle {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 0.5rem 0;
  margin: 0.5rem 0;
}

/* 移动端展开/折叠按钮容器 */
.toggle-btn-container.mobile-toggle {
  display: none; /* PC端隐藏 */
}

/* 简化的展开按钮样式 */
.toggle-btn {
  background: transparent;
  border: none;
  cursor: pointer;
  padding: 0.5rem 1rem;
  transition: all 0.3s ease;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.toggle-btn:hover {
  background: rgba(0, 0, 0, 0.05);
}

.toggle-text {
  color: #666;
  font-size: 0.9rem;
  font-weight: 500;
}

.toggle-icon {
  color: #666;
  font-size: 0.8rem;
  font-weight: normal;
  transition: transform 0.3s ease;
}

.toggle-icon.expanded {
  transform: rotate(180deg);
}

/* 展开/折叠状态样式 */
.order-meta.mobile-collapsed {
  display: none;
}

/* 新增优化样式 */

/* 优先级信息样式 */
.meta-item.priority-info {
  border-radius: 6px;
  padding: 6px 8px;
}

/* 联系信息样式 */
.meta-item.contact-info {
  border-radius: 6px;
  padding: 6px 8px;
}

/* 车牌号特殊样式 */
.meta-value.vehicle-plate {
  padding: 6px 12px;
  border-radius: 8px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 1px;
  font-family: 'Courier New', monospace;
}

/* 容器码区域优化 */
.meta-item.container-codes-section {
  border-radius: 8px;
  padding: 10px;
  margin: 8px 0;
}

.container-codes-section .meta-label {
  margin-bottom: 6px;
  font-weight: 700;
}

.container-codes-section .meta-value.container-codes {
  background: transparent;
  border: none;
  padding: 0;
  gap: 0.4rem;
  justify-content: flex-start;
}

/* 容器码标签增强 */
.container-code-tag {
  padding: 6px 12px;
  border-radius: 12px;
  font-size: 0.85rem;
  font-weight: 700;
  font-family: 'Courier New', monospace;
  letter-spacing: 0.5px;
  transition: all 0.2s ease;
  text-transform: uppercase;
  border: 1px solid #ddd;
}

.container-code-tag:hover {
  transform: translateY(-1px);
}

/* 数值显示增强 */
.meta-value.volume,
.meta-value.weight,
.meta-value.container-codes,
.meta-value.product-count,
.meta-value.stored-product-count {
  font-weight: 600;
}

/* 拥有容器样式 */
.meta-value.container-codes {
  background: transparent;
  border: none;
  padding: 0;
}

.container-codes-text {
  font-family: 'Courier New', monospace;
  font-weight: 600;
  letter-spacing: 0.5px;
  word-break: break-all;
  white-space: normal;
  line-height: 1.4;
  font-size: 0.85rem;
  color: #f8b300;
  background: rgba(248, 179, 0, 0.1);
  padding: 6px 10px;
  border-radius: 6px;
  border: 1px solid rgba(248, 179, 0, 0.3);
  display: inline-block;
  max-width: 100%;
}

/* 手机号样式 */
.meta-value.phone-number {
  font-family: 'Courier New', monospace;
  letter-spacing: 1px;
}

/* 移动端优化 */
@media (max-width: 768px) {
  /* 新增样式的移动端优化 */
  .meta-item.priority-info,
  .meta-item.contact-info {
    margin: 4px 0;
  }
  
  .meta-value.vehicle-plate {
    font-size: 0.85rem;
    padding: 6px 10px;
    letter-spacing: 0.5px;
  }
  
  .container-code-tag {
    font-size: 0.8rem;
    padding: 5px 10px;
    border-radius: 10px;
    margin: 2px;
  }
  
  .meta-item.container-codes-section {
    margin: 6px 0;
    padding: 8px;
  }
  /* 移动端展开按钮显示和样式 */
  .toggle-btn-container.pc-toggle {
    display: none; /* 移动端隐藏PC端按钮 */
  }
  
  .toggle-btn-container.mobile-toggle {
    display: flex !important; /* 移动端显示 */
    justify-content: center;
    align-items: center;
    padding: 1rem 0;
    border-top: 1px solid #e9ecef;
    margin: 0;
  }
  
  .toggle-btn {
    padding: 0.75rem 1.5rem; /* 增加内边距以适应触摸 */
    min-height: 44px; /* iOS推荐的最小触摸目标 */
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0.1);
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    user-select: none;
  }

  /* 头部操作移动端优化 */
  .main-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .new-delivery-btn, .container-manage-btn {
    flex: 1;
    justify-content: center;
    min-height: 44px;
  }
  
  .header {
    flex-wrap: wrap;
    gap: 0.5rem;
    padding: 1.5rem 1rem;
  }
  
  .header h1, .header h2 {
    font-size: 1.5rem;
  }
  
  /* 筛选按钮移动端优化 */
  .filter-toggle-btn {
    order: 3;
    width: 100%;
    margin-left: 0;
    margin-top: 0.5rem;
    padding: 0.75rem;
    font-size: 1rem;
    min-height: 44px; /* iOS推荐的最小触摸目标 */
  }
  
  .filter-row {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  /* 订单和容器项目移动端布局 */
  .order-item, .container-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
    padding: 1rem;
    margin: 8px 0;
  }
  
  .order-info, .container-info {
    width: 100%;
  }
  
  .order-actions, .container-actions {
    margin-left: 0;
    width: 80%;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
    padding: 1rem 0;
  }
  
  /* 按钮移动端优化 */
  .action-btn {
    width: 80%;
    min-height: 44px;
    font-size: 1rem;
    padding: 12px;
  }
  
  /* 筛选控制移动端优化 */
  .filter-controls {
    padding: 0.75rem 1rem;
  }
  
  /* 模态框移动端适配 */
  .modal-content {
    width: 95%;
    max-width: 95%;
    padding: 1rem;
    margin: 20px auto;
  }
  
  .modal-content.large {
    max-height: 90vh;
    overflow-y: auto;
  }
  
  /* 表单元素移动端优化 */
  .form-control {
    min-height: 44px;
    font-size: 16px; /* 防止iOS缩放 */
    padding: 12px;
  }
  
  .form-label {
    font-size: 1rem;
    margin-bottom: 0.5rem;
  }
  
  /* 加载和错误状态移动端优化 */
  .loading, .error-message {
    padding: 2rem 1rem;
    text-align: center;
    font-size: 1rem;
  }
  
  .loading-spinner {
    width: 32px;
    height: 32px;
    border-width: 3px;
  }
  
  /* 导航按钮移动端优化 */
  .back-btn, .retry-btn {
    min-height: 44px;
    padding: 0.75rem 1rem;
    font-size: 1rem;
  }
  
  /* 触摸反馈优化 */
  .new-delivery-btn, .container-manage-btn, .order-item, .container-item, .action-btn {
    -webkit-tap-highlight-color: rgba(248, 179, 0, 0.2);
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    user-select: none;
  }
  
  /* 防止移动端滚动问题 */
  .container-list, .order-items {
    -webkit-overflow-scrolling: touch;
  }
  
  /* 状态标签移动端优化 */
  .status {
    font-size: 0.9rem;
    padding: 6px 10px;
  }
  
  /* 移动端发运目的地显示 */
  .destination-display {
    flex-direction: column;
    align-items: flex-start;
    padding: 4px 0;
    margin: 2px 0;
  }
  
  .destination-label {
    margin-bottom: 0.5rem;
    margin-right: 0;
    min-width: auto;
  }
  
  .destination-value {
    width: 100%;
    text-align: left;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    border: 1px solid transparent;
    box-shadow: none;
  }
  
  /* 元数据信息移动端布局 */
  .order-meta {
    grid-template-columns: 1fr;
    gap: 0.5rem;
  }
  
  .meta-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    margin: 4px 0;
  }
  
  .meta-item:hover {
    background: rgba(248, 179, 0, 0.03);
    transform: none;
  }
  
  .meta-label {
    font-weight: 600;
    color: #444;
    min-width: auto;
    font-size: 0.9rem;
    text-transform: none;
    margin-right: 0.25rem;
    flex-shrink: 0;
    width: auto;
  }
  
  .meta-label::after {
    display: inline;
  }
  
  .meta-value {
    flex: 1;
    text-align: right;
    margin-left: 0.25rem;
    background: white;
    padding: 6px 10px;
    border-radius: 6px;
    font-size: 0.9rem;
    font-weight: 500;
    border: 1px solid transparent;
    box-shadow: none;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    min-width: 0;
  }
  
  /* 移动端容器码显示优化 */
  .container-codes-text {
    font-size: 0.75rem;
    padding: 4px 8px;
    line-height: 1.3;
    letter-spacing: 0.3px;
    max-width: 100%;
    display: block;
    text-align: left;
    margin-top: 4px;
  }
  
  .container-code-tag {
    font-size: 0.75rem;
    padding: 4px 8px;
    border-radius: 8px;
    box-shadow: 0 2px 6px rgba(248, 179, 0, 0.4);
  }
  
}

/* 空状态提示信息样式 */
.empty-containers-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 3rem 2rem;
  text-align: center;
  color: #666;
  background: #f8f9fa;
  border-radius: 12px;
  margin: 1rem 0;
  border: 2px dashed #dee2e6;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
  opacity: 0.6;
}

.empty-text h4 {
  margin: 0 0 0.5rem 0;
  color: #495057;
  font-size: 1.2rem;
  font-weight: 600;
}

.empty-text p {
  margin: 0.5rem 0;
  line-height: 1.5;
  color: #6c757d;
}

.empty-text .hint-text {
  font-size: 0.9rem;
  color: #868e96;
  font-style: italic;
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #dee2e6;
}

/* 极小屏幕设备额外优化 */
@media (max-width: 480px) {
  .container {
    padding: 10px;
  }
  
  .header {
    padding: 1rem 0.5rem;
  }
  
  .header h1, .header h2 {
    font-size: 1.25rem;
  }
  
  .function-card {
    min-height: 100px;
    padding: 1rem;
  }
  
  .card-title {
    font-size: 1rem;
  }
  
  .card-desc {
    font-size: 0.8rem;
  }
  
  .modal-content {
    width: 98%;
    padding: 0.75rem;
  }
  
  /* 已选择容器维度移动端样式 */
  .selected-containers-dimension {
    padding: 1rem;
    margin-bottom: 1rem;
  }
  
  .dimension-title {
    font-size: 1rem;
  }
  
  .container-count-badge {
    font-size: 0.8rem;
    padding: 3px 8px;
  }
  
  .container-codes-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 0.5rem;
  }
  
  .container-code-item {
    padding: 0.6rem 0.8rem;
    gap: 0.3rem;
  }
  
  .container-code-item .container-code {
    font-size: 0.8rem;
    letter-spacing: 0.3px;
  }
  
  .status-icon {
    font-size: 0.9rem;
  }
}
</style>